<template>
  <view class="page">
    <u-form :model="model" :rules="rules" ref="form" labelPosition="top" labelWidth="auto" :labelStyle="{
      fontSize: '14px',
      color: '#B2B2B2',
      lineHight: '20px'
    }">
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="billNo" required>
          <u--input v-model="model.billNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="propose" required>
          <h-select-person-input style="width: 100%" disabled v-model="model.proposer" placeholder="请选择申请人"
            border="surround" suffixIcon="arrow-down-fill" :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请时间" prop="createTime"  required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请部门" prop="proposerDeptId" required> 
          <h-select-depart-input disabled v-model="model.proposerDeptId" :departName="model.proposerDeptText"
            placeholder="请选择申请部门" border="surround" style="width: 100%" suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }" :title.sync="model.proposerDeptText"></h-select-depart-input>
        </u-form-item>
        <u-form-item label="关联项目" prop="projectId" required>
          <h-select-project-input ref="projectSelect" v-model="model.projectId" style="width: 100%" placeholder="请选择项目名称"
            objectField="model.projectId" border="surround" suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }" @input="selectProject"></h-select-project-input>
        </u-form-item>
        <u-form-item label="项目经营团队" prop="manageTeamId">
          <h-select-team-input-popup disabled style="width: 100%" v-model="model.manageTeamId"
            objectField="model.manageTeamId" placeholder="请选择项目经营团队" :tdlx="3"
            border="surround"></h-select-team-input-popup>
        </u-form-item>
        <u-form-item label="关联生产团队" prop="produceTeamId" required>
          <h-select-input-tag :disabled="!model.projectId" class="w-100" v-model="model.produceTeamId"
            objectField="model.produceTeamId" placeholder="请选择关联生产团队" border="surround" :dictName="produceTeamId"
            @change="changeProduceTeam"></h-select-input-tag>
        </u-form-item>
        <u-form-item label="项目合同总额(元)" prop="contractTotalAmount" >
          <u--input disabled type="number" v-number-normal placeholder="请输入项目合同总额" v-model="model.contractTotalAmount"></u--input>
        </u-form-item>
        <u-form-item  label="已回款金额(元)" prop="returnedAmount" >
          <u--input disabled type="number" v-number-normal placeholder="请输入已回款金额" v-model="model.returnedAmount"></u--input>
        </u-form-item>
        <u-form-item label="合同占比(%)" prop="contractRate" >
          <u--input disabled type="number" v-number-normal placeholder="请输入合同占比" v-model="model.contractRate"></u--input>
        </u-form-item>
        <u-form-item label="合同占比金额(元)" prop="contractRateAmount" >
          <u--input disabled type="number" v-number-normal placeholder="请输入合同占比金额" v-model="model.contractRateAmount"></u--input>
        </u-form-item>
        <u-form-item label="已切割金额(元)" prop="cutAmount">
          <u--input disabled type="number" v-number-normal placeholder="请输入已切割金额" v-model="model.cutAmount"></u--input>
        </u-form-item>
        <u-form-item label="本次切割金额(元)" prop="currentCutAmount" required>
					<h-money-input placeholder="请输入本次切割金额" v-model="model.currentCutAmount"></h-money-input>
        </u-form-item>
        <u-form-item label="备注" prop="remark">
          <u--textarea :confirm-type="null" maxlength="500" count placeholder="请输入备注" v-model="model.remark"></u--textarea>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.attachment" :isIcon="false"></h-upload-file>
          <file-list v-if="model.attachment" v-model="model.attachment" :isDelete="true"></file-list>
        </view>
      </view>

      <view class="space-x-1 px-1 btn_position">
        <u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
        <u-button :disabled="isSubmit" type="primary" text="保存并提交" @click="onSubmit"></u-button>
      </view>
      <view style="height: 100rpx;"></view>
    </u-form>

    <u-modal :show="confirmModal" title="是否确认" :closeOnClickOverlay="true" :asyncClose="true"
      @cancel="handleConfirmModalCancel" @confirm="handleConfirmModalConfirm" showCancelButton>
      <view class="slot-content">
        <view>是否确认切换所属团队，此操作将会清空还款明细中已填写的所有信息？</view>
      </view>
    </u-modal>
    <u-toast ref="uToast"></u-toast>
    <ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { gainBillNo, add, info, edit, queryContractManagerFinal, queryProjectTask, queryTeamCutAmount } from '@/api/finance/ErpFinanceTeamCutBillForm'
import fileList from '@/pages/synergy/components/fileList.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗

export default {
  name: 'ErpFinanceTeamCutBillForm',
  components: { fileList, ProcessNodeConfiguration },
  data() {
    return {
      produceTeamId: '',
      backUpApplicant: '',
      backUpTeamId: '',
      isReset: false,
      resetKey: '',
      index: null,
      showFormModal: false,
      confirmModal: false,
      loading: false,
      id: '',
      model: {
        // 基本信息 - 公用
        bpmBizTitle: '',
        billNo: '',
        proposer: '',
        proposerDeptId: '',
        createTime: '',
        companyId: '',
        amount: '',
        remark: '',
        // 附件
        attachment: null,
      },
      formData: [],
      rules: {
        billNo: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
				proposerDeptId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
				proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
				createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
        projectId: [{ required: true, message: '请输入关联项目!' }],
        produceTeamId: [{ required: true, message: '请输入关联生产团队!' }],
        currentCutAmount: [
          { required: true, message: '请输入本次切割金额!' },
          { pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
        ]
      },
      isSubmit: false,
      // 代码生成后需手动设置流程编码
      flowCode: 'onl_erp_finance_team_cut_bill',
      formUrl: 'erp/finance/team/modules/ErpFinanceTeamCutBillForm',
      formUrlMobile: '/pages/synergy/erpFinanceTeamCutBillList',
      beanName: 'erpFinanceTeamCutBillServiceImpl',
      processId:"",
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  created() {
    if (this.id) {
      this.initInfo()
    } else {
      this.initForm()
      this.initBillNo()
    }
  },
  computed: {
    ...mapState(['userInfo']),
    formTotal() {
      return this.formData.reduce((total, item) => total + Number(item.amount), 0).toFixed(2)
    },
  },
  methods: {
    selectProject(row) {
      if (row) {
        this.$set(this.model, 'manageTeamId', row.teamName)
        if (this.model.produceTeamId) {
          this.$set(this.model, 'cutAmount', 0)
          this.$set(this.model, 'produceTeamId', null)
          this.$set(this.model, 'contractRate', 0)
          this.$set(this.model, 'contractRateAmount', 0)
          this.produceTeamId = null
        }
        //查找对应项目的收款合同
        queryContractManagerFinal({ xmmc: row.id, htlx: 1 }).then(res => {
          if (res.success) {
            let results = res.result.records || res.result
            if (results.length > 0) {
              this.$set(this.model, 'contractTotalAmount', results[0].bchte)
              this.$set(this.model, 'returnedAmount', results[0].realCollectionPaymentMoney)
            } else {
              this.$set(this.model, 'contractTotalAmount', 0)
              this.$set(this.model, 'returnedAmount', 0)
            }
          }
        })
        queryProjectTask({ projectId: this.model.projectId }).then(res => {
          if (res.success) {
            let results = res.result.records || res.result
            if (results.length > 0) {
              let idList = results.map(item => item.productTeam)
              let idRes = idList.join('&')
              if (idRes != null && idRes != '') {
                this.produceTeamId = 'erp_omc_team_manager,alias_name,id,audit_status=2 and id in (' + idRes + ')'
              } else {
                this.produceTeamId = 'null'
              }
            } else {
              this.produceTeamId = 'null'
            }
          }
        })
      } else {
        this.produceTeamId = 'null'
        this.$set(this.model, 'manageTeamId', null)
        this.$set(this.model, 'contractTotalAmount', 0)
        this.$set(this.model, 'returnedAmount', 0)
        this.$set(this.model, 'contractRate', 0)
        this.$set(this.model, 'contractRateAmount', 0)
        this.$set(this.model, 'cutAmount', 0)
        this.$set(this.model, 'produceTeamId', null)
      }
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({ proposer: this.userInfo.empId })
      this.model.billNo = res.result
      this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.billNo //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
      this.model.payee = this.userInfo.empId //领款人
    },
    async initInfo() {
      const response = await info({ id: this.id })
      this.model = response?.result || {}
      // this.produceTeamId = 'erp_omc_team_manager,alias_name,id,audit_status=2 and id in (' + this.model.produceTeamId + ')'
      if(this.id){
				queryProjectTask({ projectId: this.model.projectId }).then(res => {
				  if (res.success) {
				    let results = res.result.records || res.result
				    if (results.length > 0) {
				      let idList = results.map(item => item.productTeam)
				      let idRes = idList.join('&')
				      if (idRes != null && idRes != '') {
				        this.produceTeamId = 'erp_omc_team_manager,alias_name,id,audit_status=2 and id in (' + idRes + ')'
				      } else {
				        this.produceTeamId = 'null'
				      }
				    } else {
				      this.produceTeamId = 'null'
				    }
				  }
				})
			}
    },
    resetProject() { },
    resetForm() { },
    validateForm() {
      return this.$refs.form.validate()
    },
    handleTeamChange(item) {
      this.model.teamYear = item.tdnd
    },
    /**
     * 团队变化弹窗点击确认
     */
    handleConfirmModalConfirm() {
      this.formData = []
      this.confirmModal = false
    },
    /**
     * 团队变化弹窗点击取消
     */
    handleConfirmModalCancel() {
      // 还原修改的数据
      if (this.resetKey) {
        let realKey = this.resetKey.replace('backUp', '')
        realKey = realKey[0].toLowerCase() + realKey.slice(1)
        this.isReset = true
        this.$set(this.model, realKey, this[this.resetKey])
        // this.$nextTick(() => {
        //   this.isReset = false
        // })
        setTimeout(() => (this.isReset = false), 0)
      }
      this.confirmModal = false
      // this.model.teamId = this.
    },
    validateCT() {
      if (!this.model.applicant) {
        uni.showToast({
          title: '请选择申请公司',
          icon: 'none',
        })
        return false
      }
      if (!this.model.teamId) {
        uni.showToast({
          title: '请选择费用所属团队',
          icon: 'none',
        })
        return false
      }
      return true
    },
    addForm() {
      if (this.validateCT()) {
        this.index = null
        this.showFormModal = true
      }
    },
    // 选择 生产团队
    changeProduceTeam(data) {
      if (data) {
        queryProjectTask({ projectId: this.model.projectId, productTeam: data }).then((res) => {
          if (res.success) {
            let results = res.result.records || res.result
            if (results.length > 0) {
              let contractRate = 0;
              let contractTotalAmount = this.model.contractTotalAmount;
              results.forEach(element => {
                contractRate += element.contractRate;
              });
              this.$set(this.model, 'contractRate', contractRate);
              this.$set(this.model, 'contractRateAmount', contractTotalAmount * contractRate * 0.01);
            }
          }
        });
        queryTeamCutAmount({ projectId: this.model.projectId, produceTeamId: data }).then((res) => {
          if (res.success) {
            let results = res.result.records || res.result
            this.$set(this.model, 'cutAmount', results);
          }
        })
      }
    },
    /**
     * 报销新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, data)
      } else {
        this.formData.push(data)
      }
    },
    async onSubmit() {
      await this.validateForm()
      this.isSubmit = true
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.model,
          slipDetailList: this.formData,
        })
        if (response.success) {
          this.isSubmit = true
          if (this.id) {
            await this.getProcessList(this.id)
          } else {
            // 判断添加的时候是否有返回id值
            if (response.result) {
              await this.getProcessList(response.result)
            }
          }
          this.isSubmit = false
        } else {
          // error
        }
      } finally {
        this.loading = false
      }
    },
    async onDraft() {
      // await this.validateForm()
      this.isSubmit = true
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.model,
          slipDetailList: this.formData,
        })
        if (response.success) {
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              this.isSubmit = false
              if (getCurrentPages().length > 1) {
                uni.navigateBack()
              } else {
                uni.reLaunch({
                  url: '/pages/home/home'
                })
              }

            }
          })
        }
      } finally {
        this.loading = false
      }
    },
    // 获取流程列表
    getProcessList(id) {
      if (this.isSubmit) {
        this.$refs.processConfig.showPopup = true
        this.$refs.processConfig.formUrl = this.formUrl
        this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        this.$refs.processConfig.flowCode = this.flowCode
        this.$refs.processConfig.edit(id, this.processId, this.beanName)
      }
    },
    // 提交流程成功
    onOk() {
      this.$refs.uToast.show({
        message: '提交成功',
        type: 'success',
        complete() {
          if (getCurrentPages().length > 1) {
            uni.navigateBack()
          } else {
            uni.reLaunch({
              url: '/pages/home/home'
            })
          }

        }
      })
    }
  },
  watch: {
    'model.applicant'(current, old) {
      if (old && current && old !== current) {
        this.backUpApplicant = old
        // this.resetMetaData()
      }
    },
    'model.teamId'(current, old) {
      if (old && current && old !== current) {
        this.backUpTeamId = old
        // this.resetMetaData()
      }
    },
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');

.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}

.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
